// 精确按照 react-easy-crop 返回的裁剪像素区域进行裁剪
export default async function getCroppedImg(imageSrc: string, croppedAreaPixels: { x: number; y: number; width: number; height: number }) {
  return new Promise<Blob | null>((resolve, reject) => {
    const image = new Image();
    image.crossOrigin = 'anonymous';
    image.onload = () => {
      try {
        const canvas = document.createElement('canvas');
        canvas.width = Math.max(1, Math.floor(croppedAreaPixels.width));
        canvas.height = Math.max(1, Math.floor(croppedAreaPixels.height));
        const ctx = canvas.getContext('2d');
        if (!ctx) return resolve(null);

        ctx.drawImage(
          image,
          croppedAreaPixels.x,
          croppedAreaPixels.y,
          croppedAreaPixels.width,
          croppedAreaPixels.height,
          0,
          0,
          canvas.width,
          canvas.height
        );

        canvas.toBlob((blob) => {
          resolve(blob);
        }, 'image/jpeg', 0.92);
      } catch (e) {
        reject(e);
      }
    };
    image.onerror = (e) => reject(e as any);
    image.src = imageSrc;
  });
}


